//
//  JobsInstallationsSearchViewController.swift
//  GreenDeal
//
//  Created by yly on 2024/5/20.
//

import UIKit
import RxGesture
import RxSwift
import RxCocoa
import SwiftyJSON
import HandyJSON

class JobsInstallationsSearchViewController: BaseViewController {
    
    fileprivate lazy var disposeBag = DisposeBag()
    let inputSearchView: JobsInputSearchView! = JobsInputSearchView(customBackToPreFlag:true)
    let resultView: JobsResultSearchView! = JobsResultSearchView(customBackToPreFlag:true)
    
    //total pages for list
    var currentPage: String = "1"
    var nextPage: String = ""
    
    var jobStr: String = ""
    var addressStr: String = ""
    var addressModel: PhysicalAddressViewModel?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.inputSearchView.titleLabel.text = R.string.localizable.search()
        self.inputSearchView.backToPreBtn.addTarget(self, action: #selector(backToPreViewController), for: UIControl.Event.touchUpInside)
        self.inputSearchView.editingChangedClosure = {[weak self](text, addressStr,addressModel ) in
            
            guard let strongSelf = self else {
                return
            }
            
            if addressStr.trimmingCharacters(in: .whitespaces) == "" , text.trimmingCharacters(in: .whitespaces) == "" ,addressModel == nil {
                return
            }
            
            
            strongSelf.jobStr = text
            strongSelf.addressStr = addressStr
            strongSelf.addressModel = addressModel
            strongSelf.loadInstallationList()
        }

        self.resultView.titleLabel.text = R.string.localizable.searchResult()
        self.resultView.backToPreBtn.addTarget(self, action: #selector(backToPreViewController), for: UIControl.Event.touchUpInside)
        self.resultView.toDetailVCClosure = {[weak self](index, operType) in
            guard let strongSelf = self else {return}
            strongSelf.toDetailVC(index,operType: operType)
        }

        self.view = inputSearchView
    }
    
    //MARK: - 退回到一步
    @objc func backToPreViewController(){
        if(self.view == resultView) {
            // 不用清理数据
//            inputSearchView.addressTextfield.text = ""
//            inputSearchView.searchTextfield.text = ""
//            inputSearchView.addressStr = ""
//            inputSearchView.addressModel = nil
//            inputSearchView.searchAddressBtn.isHidden = false
//            inputSearchView.viewTabBg.isHidden = true
//            inputSearchView.tableView.isHidden = true
//            inputSearchView.searchAddressBtn.disableBtn()
            self.view = inputSearchView;
        } else {
            if let naviVC = self.navigationController {
                naviVC.popViewController(animated: false)
            }
        }
    }

    
    /// 点击跳转
    private func toDetailVC(_ index: Int, operType: PVDsListCellOperType? = nil){
        // installations
        guard let model = self.resultView.dataObserver.value[index] as? InstallationListModel else {return}
        JobDetailModelHelper.shared.jobDetailModel = PVDDetailModel()
        JobDetailModelHelper.shared.jobDetailModel.pvd_id = model.pvd_id
        //记录Crash log时的pvd id和gwt id
        SentryHelper().setCrashLogCustomInfo(pvdId: model.pvd_id ,gwtNo: model.gwt_id)
        JobDetailModelHelper.shared.jobDetailModel.gwt_id = model.gwt_id
        JobDetailModelHelper.shared.jobDetailModel.owner_address.type_name = model.full_name
        if model.solar_water_heater {//swh
            let vc = SWHDetailViewController()
            vc.reloadPVDsListClosure = {[weak self] in
                guard let strongSelf = self else { return  }
                strongSelf.loadInstallationList(loadingFlag: false)
            }
            switch operType {
            case .barcode:
                vc.skipToWhere = .Barcode
            case .checklist:
                vc.skipToWhere = .Checklist
            case .signature:
                vc.skipToWhere = .Signature
            default:
                break
            }
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: false)
        }else{//solar
            let vc = JobDetailViewController()
            vc.reloadPVDsListClosure = {[weak self] in
                guard let strongSelf = self else { return  }
                strongSelf.loadInstallationList(loadingFlag: false)
                
            }
            switch operType {
            case .barcode:
                vc.skipToWhere = self.skipToWhereFoBarcode(model)
            case .checklist:
                vc.skipToWhere = .Checklist
            case .signature:
                vc.skipToWhere = .Signature
            case .cesfile:
                vc.skipToWhere = .CESFile
            default:
                break
            }
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    
    private func skipToWhereFoBarcode(_ model: InstallationListModel)->SkipToWhere{
        var toWhere: SkipToWhere = .Panel
        let panelCnt = (model.new_panel_number_count)
        let panelFinishCnt = (model.new_panel_number_finished_count)
        let inverterCnt = (model.inverter_number_count)
        let inverterFinishCnt = (model.inverter_number_finished_count)
        if model.is_new_stc_form && panelCnt <= panelFinishCnt && inverterCnt > inverterFinishCnt{//安装日期在2022-04-01以后的Job才这样处理，panel数量已经扫够，inverter数量不够，就跳转到Inverter，其他情况跳转到Panel
            toWhere = .Inverter
        }
        return toWhere
    }
    
    //MARK: - 根据GWTID or address 查找installation list
    private func loadInstallationList(loadingFlag: Bool = true){
        //set block
        let vm = JobsListService()
        vm.setBlockAfterNetwork({ (result, otherInfo) -> Void in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            //header data
            if let data = otherInfo?.object(forKey: "X-Next-Page") as? String{
                self.nextPage = data
            }else{
                self.nextPage = ""
            }
            //data list
            guard let res = result else {return}
            let json = JSON(res)
            if let data = JSONDeserializer<InstallationListModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<InstallationListModel>{
                if self.currentPage == "1" {
                    self.resultView.dataObserver.accept(data)
                }else{
                    let temp = data
                    self.resultView.dataObserver.accept(self.resultView.dataObserver.value + temp)
                }
                //没有数据显示not data view，有数据隐藏not data view
                self.resultView.tableView.showResultView(nodataFlag: self.resultView.dataObserver.value.count == 0 ? true : false)
                self.view = self.resultView
            }
        }) { (code, error) -> Void in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            Tool().showErrorInfo(code, error)
        }
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView()
        }
        
        let gwt_id = (self.inputSearchView.searchTextfield.text ?? "")
        let address = (self.inputSearchView.addressTextfield.text ?? "")
        var combineStr = "?page=\(self.currentPage)"
        if(gwt_id.count > 0) {
            combineStr += "&gwt_id=\(gwt_id)"
        }
        
        if(address.count > 0) {
            // 模糊地址
            combineStr += "&full_address=\(address)"
        }
        if let addressModel = addressModel {
            // 详细地址
            combineStr += "&street_number=\(addressModel.street_number)"
            combineStr += "&street_name=\(addressModel.street_name)"
            combineStr += "&street_type=\(addressModel.street_type)"
            combineStr += "&suburb=\(addressModel.suburb)"
            combineStr += "&state=\(addressModel.state)"
            combineStr += "&post_code=\(addressModel.post_code)"
        }
        vm.getInstallationsListForV2(combineStr)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
}
